package net.huashitong.Project.web;

import com.sirdc.modules.sys.filter.NodeNewschedulesModel;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import jodd.util.StringUtil;
import net.huashitong.Project.entity.NewProjects;
import net.huashitong.Project.service.EarlyWarningNodeService;
import net.huashitong.Project.service.EarlyWarningService;
import net.huashitong.Project.service.ExportService;
import net.huashitong.Project.service.NewProjectsService;
import net.huashitong.node.entity.NodeNewschedules;
import net.huashitong.node.filter.NodeNewschedulesFilter;
import net.huashitong.node.service.NodeNewschedulesService;
import net.huashitong.oversee.JobTask.JobTaskService;
import net.huashitong.oversee.entity.SupervisionTask;
import net.huashitong.oversee.service.GradePointService;
import net.huashitong.oversee.service.ScoreSummaryService;
import net.huashitong.oversee.service.SupervisionTaskService;
import net.huashitong.user.entity.BnpUser;
import net.huashitong.user.entity.Message;
import net.huashitong.user.filter.MessageFilter;
import net.huashitong.user.service.BnpUserService;
import net.huashitong.user.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static net.huashitong.Project.util.HolidayUtils.calLeaveDays;

@Controller
@RequestMapping(value = "/test")
public class TestController {

    @Autowired
    private EarlyWarningService earlyWarningService;
    @Autowired
    private JobTaskService jobTaskService;
    @Autowired
    private NodeNewschedulesService nodeNewschedulesService;
    @Autowired
    private ScoreSummaryService scoreSummaryService;
    @Autowired
    private GradePointService gradePointService;
    @Autowired
    private SupervisionTaskService supervisionTaskService;
    @Autowired
    private BnpUserService bnpUserService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private NewProjectsService newProjectsService;
    @Lazy
    @Autowired
    private ExportService exportService;

    @ResponseBody
    @RequestMapping(value = "/sentms", method = RequestMethod.GET)
    public String senMess() throws ParseException {
        earlyWarningService.remindSMS();
        return "完成";
    }


    @RequestMapping(value = "/getKLine", method = RequestMethod.GET)
    public String getKLine() throws ParseException {
        return "/modules/index/index_chart_4";
    }

    @ResponseBody
    @RequestMapping(value = "/EarlyWarningSch", method = RequestMethod.GET)
    public String EarlyWarningSch() throws ParseException {
        earlyWarningService.EarlyWarningSch();
        return "完成";
    }


    @ResponseBody
    @RequestMapping(value = "/saveSourceExpire", method = RequestMethod.GET)
    public String saveSourceExpire() throws ParseException {

        //删掉考核记录中的重复数据
        gradePointService.deleteRepeatData();
        jobTaskService.saveSourceExpire();      //自己有个定时任务
        gradePointService.updateRank();
        scoreSummaryService.updateSummaryScore();
        scoreSummaryService.updateSummaryScoreRank();
        //更新成绩到督查任务里面
        String updateScore = supervisionTaskService.updateAllTaskRespAndSupervisionScore();
        if ("ok".equals(updateScore)) {
            System.out.println("*****************更新督查任务得分完成*****************");
        }
        scoreSummaryService.updateSummaryScoreTypeRank();
        return "完成";
    }


    @ResponseBody
    @RequestMapping(value = "/haha1", method = RequestMethod.GET)
    public String haha1() throws ParseException {

        //系统排查错误时间，实际完成时间
        List<NodeNewschedules> nodeNewschedules = nodeNewschedulesService.query();
        SimpleDateFormat myFmt = new SimpleDateFormat("yyyy.MM.dd");
        List<NodeNewschedules> res = new ArrayList<>();
        for (NodeNewschedules node : nodeNewschedules) {
            if (StringUtils.isNotBlank(node.getFactFinishDate()) && StringUtils.isNotBlank(node.getPlanBeginDate())) {
                Date beginDate = myFmt.parse(node.getPlanBeginDate());
                Date finishDate = myFmt.parse(node.getFactFinishDate());
                //实际完成的天数(过滤周末)
                double t = calLeaveDays(beginDate, finishDate);
                int tin = (int) t;
                node.setFactTime(tin + "");
                res.add(node);
            }
        }
        nodeNewschedulesService.batchUpdate(res);
        return "ok";
    }

//    @ResponseBody
//    @RequestMapping(value = "/haha2", method = RequestMethod.GET)
//    public String haha2(){
//
//        //查询select * from t_bnp_node_newschedule
//        // where STATUS = '2' and fact_finish_date > '2019.06.01'
//        // and type = '2' and fact_time+0 <= plan_time+0
//        NodeNewschedulesFilter filter = new NodeNewschedulesFilter();
//        filter.setType("2");
//        filter.setStatus("2");
//        filter.setFactFinishDate("2019.06.01");
//        List<NodeNewschedules> list = nodeNewschedulesService.queryByFilter(filter);
//        List<NewProjects> projects = newProjectsService.query();
//        Map<String, NewProjects> projectsMap = new HashMap<>();
//        for (NewProjects p : projects) {
//            if (!projectsMap.containsKey(p.getSysId())) {
//                projectsMap.put(p.getSysId(), p);
//            }
//        }
//        for (NodeNewschedules node : list) {
//            String planTimeStr = node.getPlanTime();
//            String factTimeStr = node.getFactTime();
//            int palnTime = Integer.parseInt(planTimeStr);
//            int factTime = Integer.parseInt(factTimeStr);
//            if (palnTime >= factTime) {
//                NewProjects project = projectsMap.get(node.getProjectId());
//                newProjectsService.updateFullMarkPoint(node, project);
//            }
//        }
//        return "ok";
//    }

    /**
     * 更新所有督查任务的督查组得分与责任单位得分
     *
     * @return
     */
    /*@ResponseBody
    @RequestMapping(value = "/haha3", method = RequestMethod.GET)
    public String haha3() {
        //查询所有绩效得分
        List<GradePoint> gradePoints = gradePointService.query();
        //封装考核督查组的得分
        Map<String, String> supervisionScoreMap = new HashMap<>();
        //封装考核责任单位的得分
        Map<String, String> respScoreMap = new HashMap<>();
        for (GradePoint g : gradePoints) {
            if (!g.getTaskId().contains("sch_")) {
                //进入督查任务的绩效得分
                //如果考核对象是"A"开头，则表示这个考核单位是督查组
                if (g.getCheckObjectId().contains("A")) {
                    if (!supervisionScoreMap.containsKey(g.getTaskId())) {
                        supervisionScoreMap.put(g.getTaskId(), g.getSoucre());
                    }
                } else {
                    if (!respScoreMap.containsKey(g.getTaskId())) {
                        respScoreMap.put(g.getTaskId(), g.getSoucre());
                    }
                }
            }
        }
        //查询所有督查任务
        List<SupervisionTask> tasks = supervisionTaskService.query();
        for (SupervisionTask t : tasks) {
            //如果责任单位或者督查组的得分为空，则需要填充分数
            if (StringUtils.isBlank(t.getRespScore()) || StringUtils.isBlank(t.getSupervisionScore())) {
                if (StringUtils.isNotBlank(respScoreMap.get(t.getSysId()))) {
                    t.setRespScore(respScoreMap.get(t.getSysId()));
                }
                if (StringUtils.isNotBlank(supervisionScoreMap.get(t.getSysId()))) {
                    t.setSupervisionScore(supervisionScoreMap.get(t.getSysId()));
                }
            }
        }
        supervisionTaskService.batchUpdate(tasks);
        return "ok";
    }*/


    /**
     * 更新（督查任务里面添加两个字段：逾期天数、节点sysId）
     *
     * @return
     */
    /*@ResponseBody
    @RequestMapping(value = "/haha4", method = RequestMethod.GET)
    public String haha4() {
        List<SupervisionTask> tasks = supervisionTaskService.query();
        for(SupervisionTask task : tasks){
            String projectId = task.getProjectId();
            String nodeId = task.getNodeId();
            NodeNewschedules nodeNewschedules = nodeNewschedulesService.getNnsByProjectIdAndNodeId(projectId,nodeId);
            task.setNodeSysId(nodeNewschedules.getSysId());
            EarlyWarningNode earlyWarningNode = ewns.queryEarlyWarningNodeByNodeSysId(nodeNewschedules.getSysId());
            if(ObjectUtils.isBlank(earlyWarningNode)){
                continue;
            }
            task.setOverdueDays(earlyWarningNode.getNumber());
        }
        supervisionTaskService.batchUpdate(tasks);
        return "ok";
    }*/

    /**
     * 督查任务判断与否纠错代码
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/haha5", method = RequestMethod.GET)
    public String haha5() {
        List<SupervisionTask> tasks = supervisionTaskService.query();
        for (SupervisionTask task : tasks) {
            String nodeSysId = task.getNodeSysId();
            if (StringUtils.isBlank(nodeSysId)) {
                continue;
            }
            NodeNewschedules nodeNewschedules = nodeNewschedulesService.getById(nodeSysId);
            if (ObjectUtils.isNotBlank(nodeNewschedules)) {
                if ("2".equals(nodeNewschedules.getStatus())) {
                    //如果节点已完成
                    //设置责任单位任务完成
                    task.setRespResult("1");
//                    //设置督查组任务完成
//                    task.setSupervisionResult("0");
//                    task.setTaskResult("0");
                }
            }
        }
        supervisionTaskService.batchUpdate(tasks);
        return "ok";
    }

    /**
     * 督查任务添加userId,其表示节点经办人的主键
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/haha6", method = RequestMethod.GET)
    public String haha6() {
        List<SupervisionTask> tasks = supervisionTaskService.query();
        for (SupervisionTask task : tasks) {
            BnpUser user = bnpUserService.getBnpUserByPhoneAndName(task.getOperatorPhone(), task.getOperatorUser());
            if (ObjectUtils.isBlank(user)) {
                System.out.println(user);
                continue;
            }
            task.setUserid(user.getSysId());
        }
        supervisionTaskService.batchUpdate(tasks);
        return "ok";
    }


    /**
     * 修改短息消息列表中的部门字段信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/haha7", method = RequestMethod.GET)
    public String haha7() {
        List<Message> messages = messageService.query();
        for (Message message : messages) {
            BnpUser user = bnpUserService.getBnpUserByPhoneAndName(message.getPhone(), message.getRecipients());
            if (ObjectUtils.isBlank(user)) {
                System.out.println(user);
                continue;
            }
            message.setBranchType(user.getBranchType());
            message.setResDept(user.getBranch());
        }
        messageService.batchUpdate(messages);
        return "ok";
    }

    /**
     * 校验消息列表中督查组的数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/haha8", method = RequestMethod.GET)
    public String haha8() {

        MessageFilter filter = new MessageFilter();
        filter.setType("9");
        List<Message> messages = messageService.getMessageInfoNoPage(filter);
        for (Message message : messages) {
            if ("督查组".equals(message.getRecipients()) || message.getRecipients().length() > 3) {
                BnpUser bnpUser = bnpUserService.getBnpUserByPhone(message.getPhone());
                if (ObjectUtils.isBlank(bnpUser)) {
                    continue;
                }
                message.setRecipients(bnpUser.getName());
                message.setResDept(bnpUser.getBranch());
                message.setBranchType(bnpUser.getBranchType());
            }
        }
        messageService.batchUpdate(messages);
        return "ok";
    }


    /**
     * 督查任务判断与否纠错代码:督查任务结果更正
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/haha9", method = RequestMethod.GET)
    public String haha9() {
        List<SupervisionTask> tasks = supervisionTaskService.query();
        for (SupervisionTask task : tasks) {
            if ("1".equals(task.getTaskResult()) && StringUtils.isBlank(task.getEndDate())) {
                task.setEndDate(task.getPlanEndDate());
                task.setRespResult("1");
            }
            if ("0".equals(task.getTaskResult())) {
                task.setRespResult("0");
                task.setSupervisionResult("0");
            }
            if ("1".equals(task.getTaskResult())) {
                task.setSupervisionResult("1");
                task.setRespResult("1");
            }
        }
        supervisionTaskService.batchUpdate(tasks);
        return "ok";
    }

    /**
     * 督查任务被认定为失效，则绩效得分记录也清除，再进行汇总得分
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/haha10", method = RequestMethod.GET)
    public String haha10() {
        List<SupervisionTask> tasks = supervisionTaskService.query();
        //失效的督查任务
        List<String> invalidTasks = new ArrayList<>();
        for (SupervisionTask task : tasks) {
            if ("0".equals(task.getAaa001())) {
                invalidTasks.add(task.getSysId());
            }
        }
        gradePointService.deletAllInvalidTaskGradePoint(invalidTasks);
        return "ok";
    }

    /**
     * 纠正大节点实际用时跟计划用时数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/haha11", method = RequestMethod.GET)
    public String haha11() {
        List<NewProjects> projects = newProjectsService.query();
        Map<String, NewProjects> proMap = new HashMap<>();
        for (NewProjects p : projects) {
            if (!proMap.containsKey(p.getSysId())) {
                proMap.put(p.getSysId(), p);
            }
        }


        for (NewProjects p : projects) {
            List<NodeNewschedules> nodeList = nodeNewschedulesService.getNodeByProjectId(p.getSysId());
            Map<String, Integer> fMap = new HashMap<>();
            Map<String, Integer> pMap = new HashMap<>();
            for (NodeNewschedules node : nodeList) {
                //获取大节点
                if ("0".equals(node.getNodeIds()) && "1".equals(node.getType())) {
                    fMap.put(node.getNodeId(), 0);
                    pMap.put(node.getNodeId(), 0);
                }
                if (fMap.containsKey(node.getNodeIds())) {
                    Integer fCount = fMap.get(node.getNodeIds());       //实际用时
                    Integer pCount = pMap.get(node.getNodeIds());       //计划用时
                    fCount = fCount + Integer.parseInt(StringUtils.isBlank(node.getFactTime()) ? "0" : node.getFactTime());
                    pCount = pCount + Integer.parseInt(StringUtils.isBlank(node.getPlanTime()) ? "0" : node.getPlanTime());
                    fMap.put(node.getNodeIds(), fCount);
                    pMap.put(node.getNodeIds(), pCount);
                }
            }
            for (NodeNewschedules node : nodeList) {
                if ("0".equals(node.getNodeIds()) && "1".equals(node.getType())) {
                    Integer fc = fMap.get(node.getNodeId());
                    node.setFactTime(fc + "");

                    Integer pc = pMap.get(node.getNodeId());
                    node.setPlanTime(pc + "");
                }
            }
            nodeNewschedulesService.batchUpdate(nodeList);
        }

        return "ok";
    }

    /**
     * 同步小节点大节点的状态
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/synchronizationNodesStatus", method = RequestMethod.GET)
    public String synchronizationNodesStatus() {
        StringBuffer sbf = new StringBuffer();
        List<NewProjects> projectsList = newProjectsService.query();
        for (NewProjects projects : projectsList) {
            //进行中的项目
//            if("3".equals(projects.getStatus())){
            for (int i = 1; i < 37; i++) {
                //表示没有全部办结
                boolean flag = false;
                int num = 0;
                List<NodeNewschedules> nodeNewschedules = nodeNewschedulesService.getNodeIds(i + "", projects.getSysId());
                for (NodeNewschedules node : nodeNewschedules) {
                    if ("2".equals(node.getStatus())) {
                        num++;
                    }
                }
                if (num == nodeNewschedules.size() && num != 0) {
                    //表示全部办结
                    flag = true;
                }
                if (flag) {
                    NodeNewschedules bigNode = nodeNewschedulesService.getBigNodesState(projects.getSysId(), i + "");
                    if(ObjectUtils.isBlank(bigNode)){
                        System.out.println(projects.getName());
                    }else{
                        if(!"2".equals(bigNode.getStatus())){
                            bigNode.setStatus("2");
                            sbf.append("'" + bigNode.getSysId() + "',");
                            nodeNewschedulesService.update(bigNode);
                        }
//                        bigNode.setStatus("2");
//                        sbf.append("'" + bigNode.getSysId() + "',");
//                        nodeNewschedulesService.update(bigNode);
                    }
                }
            }
//            }
            sbf.append("||");
        }

        return sbf.toString();
    }
    /**
     * 同步小节点大节点的状态
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateAllProjectStartTime", method = RequestMethod.GET)
    public String updateAllProjectStartTime() throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
        //时间是2020-02-01之后做处理
        Date flagDate = simpleDateFormat.parse("2020-02-01");
        //排出项目完成时间（对单个项目进行审批）
        List<NewProjects> projects = newProjectsService.query();
        List<NewProjects> needUpdates = new ArrayList<>();
        for (NewProjects project : projects) {
            if(StringUtil.isBlank(project.getCreateDate())){
                continue;
            }
            Date createDate = simpleDateFormat.parse(project.getCreateDate());
            if(createDate.getTime() < flagDate.getTime()){
                continue;
            }
            List<String> allProjects = new ArrayList<>();
            allProjects.add(project.getSysId());
            List<NodeNewschedulesModel> models = exportService.iii(allProjects);
            List<NodeNewschedulesModel> list = new ArrayList<>();
            for (NodeNewschedulesModel model : models) {
                if("1".equals(model.getState())){
                    list.add(model);
                }
            }
            String planEndTimeFlag = list.get(list.size() - 1).getPlanEndTime();
            String factFinishDate = list.get(list.size() - 1).getFactFinishDate();
            //startTime:项目的开工时间
            project.setStartTime(StringUtils.isBlank(planEndTimeFlag) ? factFinishDate : planEndTimeFlag);
            needUpdates.add(project);
        }
        newProjectsService.batchUpdate(needUpdates);
        return "ok";
    }


}

